package com.zxl.yjb.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.umeng.commonsdk.UMConfigure;
import com.zxl.yjb.R;
import com.zxl.yjb.bean.LocationBean;
import com.zxl.yjb.im.SealAppContext;
import com.zxl.yjb.utils.NLog;
import com.zxl.yjb.utils.PathUtil;
import com.zxl.yjb.utils.SaveBeanUtil;

import java.util.List;

import cn.jpush.android.api.JPushInterface;
import io.rong.imkit.RongIM;


/**
 * Created by Administrator on 2017/5/23.
 */

public class MyApplication extends MultiDexApplication {

    /**
     * 权限请求
     */
    public static final int CAMERA_PERMISSIOM = 1;
    public static final int WRITE_EXTERNAL_STORAGE = 2;
    public static final int READ_CONTACTS = 3;
    public static final int CALL_PHONE = 4;
    public static final int SEND_SMS = 5;
    public static String currentUserNick = "";
    public static final String WXAPPID = "wxd5de35d27bd31dd3";
    public static final String WXSECRET = " ";
    public static final String MIPUSH_APP_ID = " ";
    public static final String MIPUSH_APP_KEY = " ";
    public static final String FLYME_PUSH_APP_ID = "";
    public static final String FLYME_PUSH_APP_KEY = "";

    public static String DEVICE_TYPE = "";

    public static int notificationNum = 0;

    /**
     * application的实例
     */
    public static MyApplication instance;

    public static boolean isRefresh;

    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.white_color, R.color.color_D5D5D5);
                return new ClassicsHeader(context);
            }
        });

        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.white_color, R.color.color_D5D5D5);
                ClassicsFooter classicsFooter = new ClassicsFooter(context);
                classicsFooter.setPrimaryColorId(R.color.white_color);
                classicsFooter.setAccentColorId(R.color.color_D5D5D5);
                return classicsFooter;
            }
        });
    }


    @Override
    public void onCreate() {
        MultiDex.install(this);
        super.onCreate();
        if (shouldInit()) {
            instance = this;
            registerActivityListener();
            //缓存文件路径
            PathUtil.getInstance().initDirs(Const.CACH_FILE_PATH1,Const.CACH_FILE_PATH2,this);
            initIm();
            initUmeng();
            //极光推送
            JPushInterface.setDebugMode(true);
            JPushInterface.init(this);
            getLocation();
        }
    }

    private void initUmeng() {
        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, "");
    }

    private void initIm() {
        //初始化融云IM
        RongIM.init(this);
        NLog.setDebug(true);//Seal Module Log 开关
        SealAppContext.init(this);
//        openSealDBIfHasCachedToken();
        RongIM.getInstance().setMessageAttachedUserInfo(true);
    }


    public static Context getContext() {
        return instance;
    }

    private void registerActivityListener() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                    /**
                     *  监听到 Activity创建事件 将该 Activity 加入list
                     */
                    AppManager.getInstance().addActivity(activity);

                }

                @Override
                public void onActivityStarted(Activity activity) {

                }

                @Override
                public void onActivityResumed(Activity activity) {

                }

                @Override
                public void onActivityPaused(Activity activity) {

                }

                @Override
                public void onActivityStopped(Activity activity) {

                }

                @Override
                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

                }

                @Override
                public void onActivityDestroyed(Activity activity) {
                    if (activity != null) {
                        AppManager.getInstance().finishActivity(activity);
                    }
                }
            });
        }
    }


    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }



    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }


    private void getLocation() {
        mlocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        mlocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        //定位成功回调信息，设置相关消息
                        LocationBean locationBean = new LocationBean();
                        locationBean.setLat(amapLocation.getLatitude());
                        locationBean.setLng(amapLocation.getLongitude());
                        locationBean.setCountry(amapLocation.getCountry());
                        locationBean.setProvince(amapLocation.getProvince());
                        locationBean.setCity(amapLocation.getCity());
                        locationBean.setDistrict(amapLocation.getDistrict());
                        locationBean.setStreet(amapLocation.getStreet());
                        locationBean.setAddress(amapLocation.getAddress());
                        locationBean.setCitycode(amapLocation.getCityCode());
                        locationBean.setAdCode(amapLocation.getAdCode());
                        SaveBeanUtil.putBean(getApplicationContext(),Const.LOCATION_LNGLAT,locationBean);
                    }
                }
            }
        });
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setOnceLocation(true);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setLocationCacheEnable(false);
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();
    }

}
